<template>
  <base-breadcrumb>
    <div class="about-master-container">
      <BForms ref="form">
        <a-card v-loading="loading">
          <title-name title="资产基本信息" />
          <BForm
            :config="formConfig"
            :form="form"
            :rule="formRules"
          />
        </a-card>
        <a-card v-loading="loading">
          <title-name title="配件信息" />
          <part
            ref="part"
            :disabled="disabled"
            :list.sync="form.assetAccessoriesInformations"
          />
        </a-card>
        <a-card v-loading="loading">
          <title-name title="金额与折旧信息" />
          <BForm
            :config="form2Config"
            :form="form.assetDepreciationInformation"
            :rule="formRules"
          />
        </a-card>
        <a-card v-loading="loading">
          <title-name title="责任人信息" />
          <BForm
            :config="form3Config"
            :form="form.assetResponsibleInformation"
            :rule="formRules"
          />
        </a-card>
        <a-card v-loading="loading">
          <title-name title="附件" />
          <BForm
            :config="form4Config"
            :form="form"
            :rule="formRules"
          />
        </a-card>
      </BForms>
      <div class="tar page-btn-right-top">
        <template v-if="!disabled">
          <a-button
            type="primary"
            :loading="submitLoading"
            :disabled="saveLoading"
            class="mr10p"
            @click="submit()"
          >
            提交
          </a-button>
          <a-button
            type="primary"
            :loading="saveLoading"
            :disabled="submitLoading"
            class="mr10p"
            @click="save(0,false)"
          >
            保存草稿
          </a-button>
        </template>
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>
    </div>
    <SelectPerson
      :visible.sync="modal.headPerson"
      mode="single"
      :list.sync="modal.heads"
      @getSelectPerson="selectPerson($event,1)"
    />
    <SelectPerson
      :visible.sync="modal.acceptorPerson"
      mode="single"
      :list.sync="modal.acceptors"
      @getSelectPerson="selectPerson($event,2)"
    />
  </base-breadcrumb>
</template>

<script>
import assetApi from '@/api/office/asset'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import BUploadVModel from '@/components/BComponents/BUploadVModel'
import SelectOrgDepartment from '@/components/Select/SelectOrgDepartment'
import SelectOrgPeople from '@/components/Select/SelectOrgPeople'
import SelectPerson from '@/components/Select/SelectPerson'
import part from '@/views/office/assetManagement/check/part'
import BSelect from '@/components/BComponents/BSelect'

export default {
  name: 'AssetManagementAdd',
  components: {
    SelectPerson,
    part
  },
  computed: {
    /*eslint-disable*/
    formConfig() {
      return [
        {
          row: true,
          children: [
            {
              type: SelectCompanyAndProject,
              value: 'unitId',
              label: '申请购置单位',
              show: !this.disabled,
              attrs: { disabled: this.disabled, autoSelect: !this.$route.query.id, isAuth: !this.disabled },
              on: {
                onSelectChange: e => {
                  /* eslint-disable */
                  this.form.unitName = e.name
                  this.form.depId = ''
                  this.form.depIdName = ''
                  this.form.purchaseId = ''
                  this.form.purchaseName = ''
                }
              }
            },
            {
              type: 'input', value: 'unitName', label: '申请购置单位', show: this.disabled,
              attrs: { disabled: true }
            },
            {
              type: SelectOrgDepartment,
              value: 'depId',
              label: '申请购置部门',
              attrs: {
                orgId: this.form.unitId,
                disabled: this.disabled,
                autoSelected: false,
                isAutoSelectMe: !this.$route.query.id
              },
              on: {
                onSelectChange: (e) => {
                  this.form.depName = e.name
                  this.form.purchaseId = ''
                  this.form.purchaseName = ''
                }
              }
            },
            {
              type: SelectOrgPeople,
              value: 'purchaseId',
              label: '申请购置人',
              attrs: {
                orgId: this.form.depId,
                disabled: this.disabled,
                isOrgIdNotNull: true,
                isAutoSelectMe: !this.$route.query.id
              },
              on: {
                onSelectChange: (e) => this.form.purchaseName = e.name
              }
            },
            {
              type: BSelect, value: 'assetSpecies', label: '资产类别',
              attrs: {
                disabled: this.disabled,
                request: () => assetApi.typesLabel({ type: 18 })
              },
              on: {
                change: () => {
                  this.$refs.form.clearValidate()
                  if (this.form.assetSpecies === '605004528177254572') {
                    this.form.assetType = undefined
                  }
                }
              }
            },
            {
              type: BSelect, value: 'assetType', label: '资产种类',
              show: this.form.assetSpecies === '605004528177254571',
              attrs: {
                disabled: this.disabled,
                request: () => assetApi.typesLabel({ type: 19 })
              },
              on: {
                change: (e) => {
                  this.$refs.form.clearValidate()
                  //房屋和车辆默认数量为1
                  if (e === '605004528177254575') {
                    this.form.assetName = '汽车'
                    this.form.number = 1
                  }
                  if (e === '605004528177254574') {
                    this.form.number = 1
                  }
                }
              }
            },
            {
              type: 'input', value: 'assetName', label: '资产名称',
              attrs: { disabled: this.disabled || this.form.assetType === '605004528177254575' }
            },
            {
              type: 'input', value: 'specModel', label: '规格型号',
              show: this.form.assetType === '605004528177254573' ||
                this.form.assetType === '605004528177254575' ||
                this.form.assetSpecies === '605004528177254572',
              attrs: { disabled: this.disabled }
            },
            { type: 'input', value: 'unit', label: '单位', attrs: { disabled: this.disabled } },


            /***********************资产种类：房屋建筑*****************************/
            {
              type: 'number', value: 'buildingArea', label: '建筑面积(m²)',
              show: this.form.assetType === '605004528177254574',
              attrs: { disabled: this.disabled }
            },
            {
              type: 'date-picker', value: 'completionTime', label: '竣工日期',
              show: this.form.assetType === '605004528177254574',
              attrs: { disabled: this.disabled }
            },
            {
              type: 'date-picker', value: 'useTime', label: '起用日期',
              show: this.form.assetType === '605004528177254574',
              attrs: { disabled: this.disabled }
            },
            {
              type: BSelect, value: 'housePurpose', label: '用途',
              show: this.form.assetType === '605004528177254574',
              attrs: {
                disabled: this.disabled,
                request: () => assetApi.typesLabel({ type: 20 })
              }
            },
            {
              type: 'input', value: 'houseAddress', label: '房屋地址',
              show: this.form.assetType === '605004528177254574',
              attrs: { disabled: this.disabled }
            },
            {
              type: SelectCompanyAndProject, value: 'useDepId', label: '使用单位',
              show: (!this.disabled) &&
                (this.form.assetType === '605004528177254574' || this.form.assetType === '605004528177254575'),
              attrs: { disabled: this.disabled },
              on: {
                onSelectChange: (e) => {
                  this.form.useDepName = e.name
                }
              }
            },
            {
              type: 'input', value: 'useDepName', label: '使用单位', show: this.disabled &&
                (this.form.assetType === '605004528177254574' || this.form.assetType === '605004528177254575'),
              attrs: { disabled: true }
            },
            /***********************资产种类：房屋建筑*****************************/


            /***********************资产种类：其他固定资产*****************************/
            {
              type: 'number', value: 'number', label: '数量',
              show: this.form.assetType === '605004528177254573' || this.form.assetSpecies === '605004528177254572',
              attrs: { disabled: this.disabled, precision: 2, min: 1, isInt: true }
            },
            {
              type: 'input', value: 'manufactureUnit', label: '制造单位',
              show: this.form.assetType === '605004528177254573' || this.form.assetSpecies === '605004528177254572',
              attrs: { disabled: this.disabled }
            },
            {
              type: 'input', value: 'brand', label: '品牌',
              show: this.form.assetType === '605004528177254573' || this.form.assetSpecies === '605004528177254572',
              attrs: { disabled: this.disabled }
            },
            {
              type: 'date-picker', value: 'leaveFactoryTime', label: '出厂日期',
              forceRemoveValid: true,
              show: this.form.assetType === '605004528177254573' || this.form.assetSpecies === '605004528177254572',
              attrs: { disabled: this.disabled, valueFormat: 'x' }
            },
            /***********************资产种类：其他固定资产*****************************/


            /***********************资产种类：汽车*****************************/
            {
              type: 'input', value: 'license', label: '车牌号',
              show: this.form.assetType === '605004528177254575',
              attrs: { disabled: this.disabled }
            },
            {
              type: 'date-picker', value: 'useTime', label: '起用日期',
              show: this.form.assetType === '605004528177254575',
              attrs: { disabled: this.disabled, valueFormat: 'x' }
            },
            {
              type: 'input', value: 'useAddress', label: '使用地点',
              show: this.form.assetType === '605004528177254575',
              attrs: { disabled: this.disabled }
            },
            {
              type: 'input', value: 'carPurchase', label: '用途',
              show: this.form.assetType === '605004528177254575',
              attrs: { disabled: this.disabled }
            },
            {
              type: 'input', value: 'fuelType', label: '燃油类别',
              show: this.form.assetType === '605004528177254575',
              attrs: { disabled: this.disabled }
            },
            {
              type: 'input', value: 'engineNumber', label: '发动机号',
              show: this.form.assetType === '605004528177254575',
              attrs: { disabled: this.disabled }
            },
            {
              type: 'input', value: 'chassisNumber', label: '车架号',
              show: this.form.assetType === '605004528177254575',
              attrs: { disabled: this.disabled }
            },
            {
              type: 'input', value: 'productionUnit', label: '生产单位',
              show: this.form.assetType === '605004528177254575',
              attrs: { disabled: this.disabled }
            },
            /***********************资产种类：汽车*****************************/



            {
              type: 'date-picker', value: 'acceptanceTime', label: '验收日期',
              attrs: { disabled: this.disabled, valueFormat: 'x' }
            }
          ]
        }
      ]
    },
    form2Config() {
      return [
        {
          row: true,
          children: [
            {
              type: 'number', value: 'originalValue', label: '原值(元)',
              attrs: { disabled: this.disabled, precision: 2 },
              on: { change: this.calcTotal }
            },
            {
              type: 'number', value: 'incidentals', label: '杂费(元)',
              attrs: { disabled: this.disabled, precision: 2 },
              on: { change: this.calcTotal }
            },
            {
              type: 'number', value: 'total', label: '合计金额(元)',
              attrs: { disabled: true, precision: 2, placeholder: '' }
            }
          ]
        },
        {
          row: true,
          children: [
            {
              type: 'number', value: 'durableYears', label: '使用年限(年)',
              attrs: { disabled: this.disabled, min: 1, isInt: true }
            },
            {
              type: 'number', value: 'salvage', label: '残值率(%)',
              attrs: { disabled: this.disabled, precision: 2, min: 0, max: 100 }
            }
          ]
        }
      ]
    },
    form3Config() {
      return [
        {
          row: true,
          children: [
            {
              type: 'input-search', value: 'headName', label: '负责人',
              attrs: { disabled: this.disabled },
              on: {
                click: () => this.modal.headPerson = true,
                search: () => this.modal.headPerson = true
              }
            },
            {
              type: 'input-search', value: 'acceptorName', label: '技术验收人',
              attrs: { disabled: this.disabled },
              on: {
                click: () => this.modal.acceptorPerson = true,
                search: () => this.modal.acceptorPerson = true
              }
            },
            {
              type: SelectCompanyAndProject,
              value: 'keepUnitId',
              label: '保管单位',
              show: !this.disabled,
              attrs: {
                disabled: this.disabled,
                autoSelect: !this.$route.query.id
              },
              on: {
                onSelectChange: (e) => {
                  this.form.assetResponsibleInformation.keepUnitName = e.name
                  this.form.assetResponsibleInformation.keepDepId = ''
                  this.form.assetResponsibleInformation.keepDepName = ''
                  this.form.assetResponsibleInformation.keeptorId = ''
                  this.form.assetResponsibleInformation.keeptorName = ''
                }
              }
            }
          ]
        },
        {
          row: true,
          children: [
            { type: 'input', value: 'keepUnitName', label: '保管单位', show: this.disabled, attrs: { disabled: true } },
            {
              type: SelectOrgDepartment,
              value: 'keepDepId',
              label: '保管部门',
              attrs: {
                orgId: this.form.assetResponsibleInformation.keepUnitId,
                disabled: this.disabled,
                autoSelected: false,
                isAutoSelectMe: !this.$route.query.id
              },
              on: {
                onSelectChange: (e) => {
                  this.form.assetResponsibleInformation.keepDepName = e.name
                  this.form.assetResponsibleInformation.keeptorId = ''
                  this.form.assetResponsibleInformation.keeptorName = ''
                }
              }
            },
            {
              type: SelectOrgPeople,
              value: 'keeptorId',
              label: '保管人',
              attrs: {
                orgId: this.form.assetResponsibleInformation.keepDepId,
                disabled: this.disabled,
                isOrgIdNotNull: true,
                isAutoSelectMe: !this.$route.query.id
              },
              on: {
                onSelectChange: (e) => this.form.assetResponsibleInformation.keeptorName = e.name
              }
            }
          ]
        }
      ]
    },
    form4Config() {
      return [
        {
          row: true,
          children: [
            {
              type: BUploadVModel, value: 'assetEnquiryFiles', label: '资产询价记录', colSpan: 24,
              show: this.form.assetSpecies === '605004528177254571',
              attrs: { disabled: this.disabled, businessCode: 'UN09' }
            },
            {
              type: BUploadVModel, value: 'assetPurchaseFiles', label: '购置申请', colSpan: 24,
              attrs: { disabled: this.disabled, businessCode: 'UN09' }
            },
            {
              type: BUploadVModel, value: 'assetContract', label: '购置合同', colSpan: 24,
              show: this.form.assetSpecies === '605004528177254571',
              attrs: { disabled: this.disabled, businessCode: 'UN09' }
            },
            {
              type: BUploadVModel, value: 'assetInvoiceFiles', label: '发票复印件', colSpan: 24,
              attrs: { disabled: this.disabled, businessCode: 'UN09' }
            },
            {
              type: BUploadVModel, value: 'assetAcceptance', label: '资产验收单', colSpan: 24,
              attrs: { disabled: this.disabled, businessCode: 'UN09' }
            },
            {
              type: BUploadVModel, value: 'assetDirector', label: '局董事会决议', colSpan: 24,
              show: this.form.assetSpecies === '605004528177254571',
              attrs: { disabled: this.disabled, businessCode: 'UN09' }
            },
            {
              type: BUploadVModel, value: 'assetOtherFiles', label: '其他', colSpan: 24,
              attrs: { disabled: this.disabled, businessCode: 'UN09' }
            }
          ]
        }
      ]
    },
    loading() {
      return this.submitLoading || this.saveLoading
    }
  },
  data() {
    return {
      submitLoading: false,
      saveLoading: false,
      modal: {
        headPerson: false,
        acceptorPerson: false,
        acceptors: [],
        heads: []
      },
      disabled: this.$route.query.detail == 1,
      isFirst: true,
      form: {
        'acceptanceTime': null,
        'useDepId': undefined,
        'useDepName': '',
        'accessories': null,
        'assetName': null,
        'assetSpecies': undefined,
        'assetType': undefined,
        'brand': '',
        'buildingArea': null,
        'carPurchase': null,
        'chassisNumber': null,
        'completionTime': null,
        'depId': '',
        'depName': '',
        'engineNumber': null,
        'fuelType': null,
        'houseAddress': null,
        'housePurpose': undefined,
        'leaveFactoryTime': '',
        'license': null,
        'manufactureUnit': '',
        'number': null,
        'productionUnit': null,
        'purchaseId': '',
        'purchaseName': '',
        'specModel': '',
        'status': '',
        'unit': '',
        'unitId': '',
        'unitName': '',
        'useAddress': null,
        'useDep': null,
        'useTime': null,
        'assetCode': null,
        'assetAccessoriesInformations': [],
        'assetDepreciationInformation': {
          'baseId': '',
          'durableYears': '',
          'id': '',
          'incidentals': '',
          'originalValue': '',
          'salvage': '',
          'time': '',
          'discountMonth': '',
          'discountMoney': '',
          'netValue': '',
          'salvageValue': '',
          'total': ''
        },
        'assetResponsibleInformation': {
          'acceptorId': '',
          'acceptorName': '',
          'baseId': '',
          'headId': '',
          'headName': '',
          'id': '',
          'keepDepId': '',
          'keepDepName': '',
          'keepUnitId': '',
          'keepUnitName': '',
          'keeptorId': '',
          'keeptorName': ''
        },

        'assetEnquiryFiles': [],
        'assetInvoiceFiles': [],
        'assetOtherFiles': [],
        'assetPurchaseFiles': [],
        'assetContract': [],
        'assetAcceptance': [],
        'assetDirector': [],


        'assetSpeciesStr': '',
        'assetTypeStr': null,
        'housePurposeStr': null,
        'statusStr': '',
        'assetDisposal': null,
        'assetDisposalApplyFiles': null,
        'assetDisposalPhotoFiles': null,
        'assetAuthenticateFiles': null,
        'assetDisposalFiles': null,
        'disposalId': null,
        'disposalName': null,
        'disposalTime': null
      },
      form1:{
        'assetAccessoriesInformations': [],
        'assetDepreciationInformation': {
          'baseId': '',
          'durableYears': '',
          'id': '',
          'incidentals': '',
          'originalValue': '',
          'salvage': '',
          'time': '',
          'discountMonth': '',
          'discountMoney': '',
          'netValue': '',
          'salvageValue': '',
          'total': ''
        },
        'assetResponsibleInformation': {
          'acceptorId': '',
          'acceptorName': '',
          'baseId': '',
          'headId': '',
          'headName': '',
          'id': '',
          'keepDepId': '',
          'keepDepName': '',
          'keepUnitId': '',
          'keepUnitName': '',
          'keeptorId': '',
          'keeptorName': ''
        },

        'assetEnquiryFiles': [],
        'assetInvoiceFiles': [],
        'assetOtherFiles': [],
        'assetPurchaseFiles': [],
        'assetContract': [],
        'assetAcceptance': [],
        'assetDirector': [],
      },
      formRules: {
        assetEnquiryFiles: { type: 'array', required: true, message: '请上传资产询价记录', trigger: 'change' },
        // assetOtherFiles: { type: 'array', required: true, message: '请上传其他', trigger: 'change' },
        assetInvoiceFiles: { type: 'array', required: true, message: '请上传发票复印件', trigger: 'change' },
        assetPurchaseFiles: { type: 'array', required: true, message: '请上传购置申请', trigger: 'change' },
        assetContract: { type: 'array', required: true, message: '请上传购置合同', trigger: 'change' },
        assetAcceptance: { type: 'array', required: true, message: '请上传资产验收单', trigger: 'change' },
        // assetDirector: { type: 'array', required: true, message: '请上传局董事会决议', trigger: 'change' },

        acceptanceTime: { required: true, message: '验收日期不能为空', trigger: 'change' },
        accessories: { required: true, message: '配件信息不能为空', trigger: 'blur' },
        durableYears: { required: true, message: '使用年限（年）不能为空', trigger: 'blur' },
        // incidentals: { required: true, message: '杂费（元）不能为空', trigger: 'blur' },
        originalValue: { required: true, message: '原值（元）不能为空', trigger: 'blur' },
        salvage: { required: true, message: '残值率（%）不能为空', trigger: 'blur' },
        assetName: { required: true, message: '资产名称不能为空', trigger: 'blur' },
        assetSpecies: { required: true, message: '资产类别不能为空', trigger: 'change' },
        assetType: { required: true, message: '资产种类不能为空', trigger: 'change' },
        brand: { required: true, message: '品牌不能为空', trigger: 'blur' },
        buildingArea: { required: true, message: '建筑面积不能为空', trigger: 'blur' },
        carPurchase: { required: true, message: '车辆用途不能为空', trigger: 'blur' },
        chassisNumber: { required: true, message: '车架号不能为空', trigger: 'blur' },
        completionTime: { required: true, message: '竣工日期不能为空', trigger: 'change' },
        depId: { required: true, message: '申请购置部门不能为空', trigger: 'blur' },
        engineNumber: { required: true, message: '发动机号不能为空', trigger: 'blur' },
        fuelType: { required: true, message: '燃油类别不能为空', trigger: 'blur' },
        houseAddress: { required: true, message: '房屋地址不能为空', trigger: 'blur' },
        housePurpose: { required: true, message: '房屋用途不能为空', trigger: 'blur' },
        // leaveFactoryTime: { required: true, message: '出厂日期不能为空', trigger: 'change' },
        license: { required: true, message: '车牌号不能为空', trigger: 'blur' },
        manufactureUnit: { required: true, message: '制造单位不能为空', trigger: 'blur' },
        number: { required: true, message: '数量不能为空', trigger: 'blur' },
        productionUnit: { required: true, message: '生产单位不能为空', trigger: 'blur' },
        purchaseId: { required: true, message: '申请购置人不能为空', trigger: 'blur' },
        specModel: { required: true, message: '规格型号不能为空', trigger: 'blur' },
        unit: { required: true, message: '单位不能为空', trigger: 'blur' },
        unitId: { required: true, message: '申请购置单位不能为空', trigger: 'change' },
        useAddress: { required: true, message: '使用地点不能为空', trigger: 'blur' },
        useDepId: { required: true, message: '使用单位不能为空', trigger: 'blur' },
        useTime: { required: true, message: '起用日期不能为空', trigger: 'change' },
        acceptorName: { required: true, message: '技术验收人不能为空', trigger: 'blur' },
        headName: { required: true, message: '负责人不能为空', trigger: 'blur' },
        keepDepId: { required: true, message: '保管部门不能为空', trigger: 'change' },
        keepUnitId: { required: true, message: '保管单位不能为空', trigger: 'change' },
        keeptorId: { required: true, message: '保管人不能为空', trigger: 'change' }
      }
    }
  },
  created: async function() {
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      await this.getBaseInfo()
    }
  },
  methods: {
    calcTotal() {
      this.form.assetDepreciationInformation.total =
        this.form.assetDepreciationInformation.originalValue +
        this.form.assetDepreciationInformation.incidentals
    },
    selectPerson(e, type) {
      if (!e) return
      if (type === 2) {
        this.form.assetResponsibleInformation.acceptorId = e[0].userId
        this.form.assetResponsibleInformation.acceptorName = e[0].name
      } else {
        this.form.assetResponsibleInformation.headId = e[0].userId
        this.form.assetResponsibleInformation.headName = e[0].name
      }
    },
    async getBaseInfo() {
      this.saveLoading = true
      let res = await assetApi.findById({}, { id: this.form.id })
      if (res.code === this.SUCCESS_CODE) {
        this.form = res.data
        this.modal.acceptors = [{
          userId: this.form.assetResponsibleInformation.acceptorId,
          name: this.form.assetResponsibleInformation.acceptorName
        }]
        this.modal.heads = [{
          userId: this.form.assetResponsibleInformation.headId,
          name: this.form.assetResponsibleInformation.headName
        }]
      }
      this.saveLoading = false
    },
    async submit() {
      if (!await this.save(0, true)) {
        return
      }
      if (await this.save(1, true)) {
        this.$close()
      }
    },
    async save(auditStatus, isSubmit = false) {
      return new Promise(async resolve => {
        let isPass = true
        if (isSubmit) {
          if (this.$refs.part.editingIndex !== null) return this.$noticeWarning('请结束配件当前行再操作')
          this.$refs.form.validate(valid => {
            isPass = valid
          })
        } else {
          isPass = true
        }
        if (isPass) {
          let res
          let temp = this.$clone(this.form)
          temp.status = auditStatus
          if (!isSubmit) {
            this.saveLoading = true
          } else {
            this.submitLoading = true
          }
          if (temp.id) {
            res = await assetApi.update(temp)
          } else {
            res = await assetApi.add(temp)
          }
          if (res.code === 200) {
            this.form.id = res.data.id
            await this.getBaseInfo()
            if (auditStatus === 0) {
              if (!isSubmit) {
                this.$message.success('保存成功')
              }
            } else {
              this.$message.success('提交成功')
            }
            resolve(true)
          }
          this.saveLoading = false
          this.submitLoading = false
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>
